package net.zjitc.yaobei_backed.service.sms.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.zjitc.yaobei_backed.config.SmsConfig;
import net.zjitc.yaobei_backed.service.sms.SmsProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 聚合数据短信服务商实现
 */
@Component
public class JuheSmsProvider implements SmsProvider {
    
    @Autowired
    private SmsConfig smsConfig;
    
    private RestTemplate restTemplate;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Autowired(required = false)
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    
    /**
     * 获取RestTemplate实例，如果没有注入则创建默认实例
     */
    private RestTemplate getRestTemplate() {
        if (restTemplate == null) {
            restTemplate = new RestTemplate();
        }
        return restTemplate;
    }
    
    @Override
    public boolean sendVerificationCode(String phone, String code) throws Exception {
        SmsConfig.JuheConfig config = smsConfig.getJuhe();
        
        if (config.getApiKey() == null || config.getApiKey().isEmpty() || 
            config.getApiKey().equals("your-juhe-api-key")) {
            throw new IllegalArgumentException("聚合数据API Key未配置");
        }
        
        // 构建请求参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("mobile", phone);
        params.add("tpl_id", config.getTemplateId());
        params.add("tpl_value", "#code#=" + code);
        params.add("key", config.getApiKey());
        
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
        
        // 发送请求
        ResponseEntity<String> response = getRestTemplate().postForEntity(
            config.getUrl(), 
            request, 
            String.class
        );
        
        // 解析响应
        String responseBody = response.getBody();
        if (responseBody == null) {
            throw new Exception("聚合数据API返回空响应");
        }
        
        JsonNode jsonNode = objectMapper.readTree(responseBody);
        int errorCode = jsonNode.get("error_code").asInt();
        
        if (errorCode == 0) {
            return true;
        } else {
            String reason = jsonNode.has("reason") ? jsonNode.get("reason").asText() : "未知错误";
            throw new Exception("聚合数据短信发送失败: " + reason + " (错误码: " + errorCode + ")");
        }
    }
    
    @Override
    public String getProviderName() {
        return "聚合数据";
    }
}

